package Multithreading.Thread.test.ThreadLocalAndSynchronized;

//
/**
 * todo ThreadLocal: 同步机制采用了  “ 空间换时间 ” 的方式为每一个线程都提供了一份变量副本
 *     多线程中每个线程之间的变量数据相互隔离
 * */
public class ThreadLocalDemo {
    ThreadLocal<String> threadLocal = new ThreadLocal<>();
    //变量
    private String content;

    private String getContent(){
        String s = threadLocal.get();
        return s;
    }

    private void setContent(String content){
        // 将便变量绑定当前变量
        threadLocal.set(content);
    }

    public ThreadLocalDemo() {
    }

    public ThreadLocalDemo(String content) {
        this.content = content;
    }

    @Override
    public String toString() {
        return "Demo2{" +
                "content='" + content + '\'' +
                '}';
    }

    public static void main(String[] args) {
        ThreadLocalDemo threadLocalDemo = new ThreadLocalDemo();
        for(int i = 0; i< 5; i++){
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    threadLocalDemo.setContent(Thread.currentThread().getName() + "的数据");
                    System.out.print("\t ----- \t");
                    System.out.println(Thread.currentThread().getName() + "--->" + threadLocalDemo.getContent());
                }
            },"线程"+i);
            thread.start();
        }
        System.out.println("");
    }
}
